/******************************************************************************
 * 
 *****************************************************************************/

package com.gw.business.analysis.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gw.business.analysis.model.UserTrackDataException;
import com.gw.business.analysis.service.ExceptionTrackService;
import com.gw.business.common.util.DateUtil;
import com.gw.business.common.util.EmailConfig;
import com.gw.business.statistics.exception.model.ExceptionEmail;
import com.gw.business.system.semil.model.EmailSetModel;
import com.gw.platform.service.impl.DefaultService;
import com.gwghk.gaims.mail.client.SendingEmailClient;

/**
 * 异常信息处理类
 * 
 * @author kidy
 * @since 1.0
 * @version 2015年2月10日 kidy
 */
@Service
public class ExceptionTrackServiceImpl extends DefaultService implements ExceptionTrackService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionTrackServiceImpl.class);
    
    // 获取邮件配置用户数据
    public List<EmailSetModel> queryEmail(String typeTemp) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("typeTemp", typeTemp);
        return (List<EmailSetModel>) this.find("getEmailSet", param);
    }
    
    /**
     * 处理异常信息
     */
    public void dealExceptionInfo() {
        
        try {
            LOGGER.info("处理异常dealExceptionInfo start ");
            String startTime = DateUtil.getDateFormat(DateUtil.addMinutes(new Date(), -10), "yyyy-MM-dd HH:mm");
            String endTime = DateUtil.getDateFormat(new Date(), "yyyy-MM-dd HH:mm");
            String nowTime = DateUtil.getDateFormat(new Date(), "yyyy-MM-dd ");
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("startTime", startTime);
            param.put("endTime", endTime);
            param.put("nowTime", nowTime);
            //获取前10分钟的异常数据
            List<ExceptionEmail> exceptionList = (List<ExceptionEmail>) this.find("getException", param);
            LOGGER.info("dealExceptionInfo param 开始时间startTime>>" + startTime + "结束时间：endTime>>" + endTime + "获取异常数据" + exceptionList.size());
            StringBuffer userIds = new StringBuffer();
            Set<String> userSetList = new HashSet<String>();
            Set<String> userExSetList = new HashSet<String>();
            if (exceptionList != null && exceptionList.size() >= 1) {
                // 异常记录最少要到10条
                for (ExceptionEmail emailTemp : exceptionList) {
                    if(emailTemp.getUserCount()>=10){
                    userSetList.add(emailTemp.getUserId());
                    }
                }
                  
                    //获取有异常的用户集合
                    if (userSetList != null && userSetList.size() > 0) {
                        for (String userId : userSetList) {
                                    //如果用户对应的异常数据有10调，则判断该用户当天是否已经发送过异常数据
                                    userIds.append("用户："+userId).append(",IP:"+exceptionList.get(0).getIp());
                               
                                    param.put("userId", userId);
                                    List<UserTrackDataException> dataList =
                                        (List<UserTrackDataException>) this.find("getUserSendExceptionState", param);
                                   
                                    if (null != dataList && dataList.size() > 0) {
                                        // 表示该用户当天已经发送过一次邮件通知
                                    } else {
                                     
                                        userExSetList.add(userId);
                                    }
                                }
                        }
                        
                        if(null!=userExSetList&&userExSetList.size()>0){
                            for (String userId : userSetList) {
                              
                                param.put("userIds", userId);
                                this.update("updateDataExceptionSendState", param);
                            }
                            
                            //标示需要发送已经邮件的用户为已发送
                            // 如果有30分钟执行操作的用户，则发送邮件通知
                            List<EmailSetModel> emailList = (List<EmailSetModel>) this.find("getEmailSet", null);
                            if (null != emailList && emailList.size() > 0) {
                                
                                for (EmailSetModel email : emailList) {
                                    StringBuffer buf = new StringBuffer();
                                    buf.append("<p>您好：" + email.getUserName() + "</p>");
                                    buf.append("<p>" + userIds + "</p><p>连续10分钟内，每分钟查看的页面数超过10个,查看详情请登录用户访问追踪系统</p>");
                                    // subject 主题 content 内容 fromEmail 发件箱地址 fromEmailDisplayName 别名 toEmail 收件箱
                                   
                                    SendingEmailClient.sendMail(EmailConfig.getValue("sendMailSimple_goldMailApiUrl"), "GWFX", startTime+" 点击异常", buf.toString(),
                                        null, false, EmailConfig.getValue("fromEmail"), "", email.getEmail(), null);
                                }
                                
                            
                                
                            }
                        }
                    
                }
            
            
        } catch (Exception e) {
            LOGGER.error("dealExceptionInfo exception", e);
        }
    }
}
